// import Vue from "vue";
// import Vuex from "vuex";

// Vue.use(Vuex);

export const ROUTE_PREFIX = new RegExp(/\/\$statistics/);
export const ROUTE_PREFIX_USERMANAGER = new RegExp(/\/userManager/);
// 如果需要去掉文件夹，可以在生产路由的时候用这个
// export const ROUTE_PREFIX_PATH = new RegExp(/\/DataStatistics/);

// 路由生成器
const routeGenerator = (route) => {
  const BasicConfig = {
    path: route.path.replace(ROUTE_PREFIX, ""),
    name: route.name,
    meta: {
      title: route.title,
    },
  };
  return route.component
    ? {
        ...BasicConfig,
        component: () =>
          import(
            /* webpackChunName: "[request]" */ `@/views${route.component}.vue`
          ),
      }
    : BasicConfig;
};

export default new Vuex.Store({
  state: {
    menu: [],
    permission: [],
    asyncRoute: [],
  },
  getters: {
    $menu: (state) => state.menu,
    $permission: (state) => state.permission,
    $asyncRoute: (state) => state.asyncRoute,
  },
  mutations: {
    ET_MENUS(state, payload) {
      state.menu = payload;
    },
    SET_PERMISSION(state, payload) {
      state.permission = payload;
    },
    SET_ASYNCROUTE(state, payload) {
      state.asyncRoute = payload;
    },
  },
  actions: {
    $setMenus({ commit }, _) {
      // 匹配statistics的路由
      const payload = _.filter(
        (item) =>
          item.path.match(ROUTE_PREFIX)
      );
      // 这里保存菜单
      commit("ET_MENUS", payload);

      // 构建路由
      let routes = [];

      payload.map((item) => {
        if (item.type === 1) {
          routes.concat(routeGenerator(item));
        }

        routes.push({ ...routeGenerator(item) });

        if (Array.isArray(item.children)) {
          routes = routes.concat(
            item.children
              .filter((child) => child.type === 1)
              .map((child) => routeGenerator(child))
          );
        }

        // 这里保存路由
        commit("SET_ASYNCROUTE", [...routes]);
      });

    },
    // 这里保存权限
    $setPermission({ commit }, payload) {
      commit("SET_PERMISSION", payload);
    },
  },
  modules: {},
});
